package com.chengyi.serialport.demo.utils

import java.util.concurrent.ConcurrentHashMap

class ExpirableFunction2<T1, T2>(private val expireMillSecond: Long) {
    private val cacheMap = ConcurrentHashMap<Long, (T1, T2) -> Unit>()

    fun add(callback: (T1, T2) -> Boolean) {
        val key = System.currentTimeMillis()
        val newCallback = { t1: T1, t2: T2 ->
            if (callback(t1, t2)) {
                cacheMap.remove(key)
            }
        }
        cacheMap[key] = newCallback
    }

    fun set(callback: (T1, T2) -> Boolean) {
        cacheMap.clear()
        add(callback)
    }

    fun getUnExpired(): List<(T1, T2) -> Unit> {
        val now = System.currentTimeMillis()
        val result = arrayListOf<(T1, T2) -> Unit>()
        val keys = arrayListOf<Long>()
        keys.addAll(cacheMap.keys)
        for (key in keys) {
            if (now - key >= expireMillSecond) {
                cacheMap.remove(key)
            } else {
                cacheMap[key]?.let(result::add)
            }
        }
        return result
    }
}